﻿using AutoMapper;
using DataServer.ApplicationLib.Entities;
using DataServer.ApplicationLib.Repositories;
using DataServer.CommonLib.Models.DataSource;
using Swimj.CommonLib.Base;
using Swimj.DataCore;

namespace DataServer.ApplicationLib.Services
{
    public class DataSourceService : IDataSourceService
    {
        private readonly IDataSourceRepository _dataSourceRepository;
        private readonly IMapper _mapper;

        public DataSourceService(IDataSourceRepository dataSourceRepository,
            IMapper mapper)
        {
            _dataSourceRepository = dataSourceRepository;
            _mapper = mapper;
        }

        public async Task<PaginatedResult<DataSourceInfoResponseDto>> QueryDataSourcesByPageAsync(
            DataSourceSearchRequestDto model)
        {
            var conditionCollection = new ConditionCollection();
            if (model != null)
            {
                // if (!string.IsNullOrEmpty(model.DatabaseName))
                // {
                //     conditionCollection.Add(nameof(DataBaseEntity.DatabaseName), model.DatabaseName,
                //         ConditionType.Contains);
                // }

                var result =
                    await _dataSourceRepository.QueryFilterByPageAsync(conditionCollection, model.Page, model.Limit);

                return await PaginatedResult<DataSourceInfoResponseDto>.SuccessAsync(
                    _mapper.Map<List<DataSourceInfoResponseDto>>(result.Item1),
                    result.Item2,
                    model.Page, model.Limit);
            }

            return await PaginatedResult<DataSourceInfoResponseDto>.SuccessAsync(new List<DataSourceInfoResponseDto>(),
                0, 0, 0);
        }

        public async Task<Result<IList<DataSourceInfoResponseDto>>> QueryDataSourcesAsync(DataSourceSearchRequestDto model)
        {
            var conditionCollection = new ConditionCollection();
            if (model != null)
            {
                // if (!string.IsNullOrEmpty(model.DatabaseName))
                // {
                //     conditionCollection.Add(nameof(DataBaseEntity.DatabaseName), model.DatabaseName,
                //         ConditionType.Contains);
                // }
            }

            var result = await _dataSourceRepository.QueryFilterAsync(conditionCollection);
            return await Result<IList<DataSourceInfoResponseDto>>.SuccessAsync(
                _mapper.Map<List<DataSourceInfoResponseDto>>(result));
        }

        public async Task<Result<DataSourceInfoResponseDto>> CreateDataSourceAsync(DataSourceEditRequestDto model)
        {
            var dataSourceEntity = _mapper.Map<DataSourceEntity>(model);

            await _dataSourceRepository.InsertAsync(dataSourceEntity);

            return await Result<DataSourceInfoResponseDto>.SuccessAsync(
                _mapper.Map<DataSourceInfoResponseDto>(dataSourceEntity));
        }
    }
}